package com.chanzany.singleton.type4;


public class SingletonTest {
    public static void main(String[] args) throws InterruptedException {
//        Singleton instance = Singleton.getInstance();
//        Singleton instance2 = Singleton.getInstance();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                Singleton instance = Singleton.getInstance();
            }).start();
        }
    }
}

/**
 * 懒汉式（线程安全，效率低）
 */
class Singleton{
    private Singleton(){}
    private static Singleton instance;
    //加入同步代码，解决线程安全问题
    public synchronized static Singleton getInstance(){
        if (instance==null) {
            instance = new Singleton();
        }
        return instance;
    }
}
